package main

import (
	"3nets.io/wireguardcommon"
	"crypto"
	"flag"
	"fmt"
	"log"
)

func main() {
	var err error
	var managerPrivate crypto.PrivateKey
	var managerPublic crypto.PublicKey
	var managerPublicBytes [32]byte
	var managerPrivateBytes [32]byte

	edgePublicPtr := flag.String("edgePublic", "", "the public part from edge")
	edgeName := flag.String("edgeName", "3netsedge.io", "The name of the edge")
	generateSignatureUrl := flag.String("generateSignatureUrl", "http://test1.jagat.me:8123/nacl-sign", "The url to use for generating Signature")
	flag.Parse()

	managerPrivate, managerPublic, err = wireguardcommon.GenerateKeyPair()
	if err != nil {
		fmt.Printf("Failed to generate manager private/public key pair: %s\n", err)
		return
	}
	if ok := wireguardcommon.CheckType(&managerPrivateBytes, managerPrivate); !ok {
		panic("ecdh: unexpected type of manager public key")
	}
	if ok := wireguardcommon.CheckType(&managerPublicBytes, managerPublic); !ok {
		panic("ecdh: unexpected type of manager public key")
	}

	fmt.Println("edgePublic=", *edgePublicPtr)
	fmt.Println("edgeName=", *edgeName)
	fmt.Println("generateSignatureUrl=", *generateSignatureUrl)

	if *edgePublicPtr != "" {
		presharedKey, err := wireguardcommon.GenPskOnManager(*edgePublicPtr, managerPrivate)
		if err != nil {
			fmt.Printf("Failed to generate manager private/public key pair: %s\n", err)
			return
		} else {
			fmt.Printf("presharedkey=%s\n", presharedKey)
		}
	} else {
		if *edgeName != "" {
			signature, err := wireguardcommon.GenerateSignature(*generateSignatureUrl, *edgeName)
			if err != nil {
				log.Fatalf("Cant reach the url for generating signature, %s", err)
			}
			fmt.Printf("edgeSignature: %s\n", signature)
		} else {
			log.Fatalf("edgeName is required")
		}
	}
}
